<template>
  <div class="chat-page" style="background: linear-gradient(45deg, rgb(253 249 237) 0%, rgb(199 236 253) 100%);">
    <!-- 顶部导航栏 -->
    <!-- <van-nav-bar title="AI 助手" left-text="返回" left-arrow @click-left="$router.go(-1)" /> -->
    <div style="position: relative; margin: 0px auto; width: 100%; height: 180px; margin-bottom: 30px;">
      <van-icon name="arrow-left" color="#ffffff" size="2rem" style="position: absolute; top: 4%; left: 2%;"
        @click="$router.go(-1)" />
      <!-- <van-icon name="cross" color="#ffffff" size="2rem" style="position: absolute; top: 2%; right: 2%;" /> -->
      <img src="@/assets/AI_yuan.png" alt="" srcset=""
        style="position: absolute; top: 96%; right: 7%; width: 30%; cursor: pointer;">
      <img src="@/assets/AI_ren5.png" alt="" srcset=""
        style="position: absolute; top: 10%; right: 6%; width: 30%; cursor: pointer;">
      <img src="@/assets/AI_biaoyu.png" alt="" srcset=""
        style="position: absolute; top: 10%; left: 8%; width: 50%; cursor: pointer;">
      <div style="position: absolute; top: 60%; left: 8%; width: 50%; cursor: pointer;">
        <div style=""><strong>Hi~，有什么要咨询的吗?</strong></div>
        <div style="font-size: small;">您好，我是AI小助手，您的政务服务智能助手，有问题尽管问我哦~</div>
      </div>
    </div>
    <!-- 消息容器 -->
    <div ref="messageContainer" class="message-container">
      <div>
        <van-cell-group inset style="margin:0">
          <van-tabs v-model:active="active" shrink>
            <van-tab v-for="questions in questionsList" :title="questions.title" :key="questions.title">
              <van-cell v-for="item in questions.list" :title="item.title" is-link
                style="--van-cell-vertical-padding: 1.5vmin" @click="sendQuestionsMessage(item)" />
            </van-tab>
          </van-tabs>
        </van-cell-group>

      </div>
      <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role, { 'thinking': msg.isThinking }]">
        <!-- AI头像 -->
        <!-- <van-image v-if="msg.role === 'assistant'" round width="36" height="36" :src="aiAvatar" /> -->
        <!-- 消息气泡 -->
        <div class="bubble">
          <!-- 加载状态 -->
          <van-loading v-if="msg.loading" size="20" type="spinner" vertical>思考中...</van-loading>
          <!-- 消息内容 -->
          <div v-else-if="msg.role === 'user'">{{ msg.answer }}</div>
          <!-- 消息内容 -->
          <template v-else>
            <!-- 思考阶段内容 -->
            <div v-if="msg.thinking" class="thinking-phase">
              <div class="thinking-icon"
                style="color: rgb(38, 38, 38); margin-bottom: 12px;font-size: 12px;line-height: 18px;">💡 已深度思考</div>
              <div class="markdown-body" v-html="htmlContent(msg.thinking)"></div>
            </div>

            <!-- 正式回答内容 -->
            <div v-if="msg.answer" class="answer-phase">
              <div v-if="msg.thinking" class="answer-header">📖 正式回答</div>
              <div class="answer-content" v-html="htmlContent(msg.answer)"></div>
            </div>
          </template>
        </div>
        <!-- 用户头像 -->
        <!-- <van-image v-if="msg.role === 'user'" round width="36" height="36" :src="userAvatar" /> -->
      </div>
    </div>
    <!-- 输入区域 -->
    <div class="input-area">
      <van-field v-model="inputMessage" rows="1" autosize type="textarea" placeholder="请输入问题..."
        @keyup.enter.exact.prevent="sendMessage" />
      <van-button plain type="primary" @click="sendMessage" :loading="isLoading" :icon="svgIconPath" style="--van-button-border-width: 0;
      --van-button-icon-size: 36px;"></van-button>
      <!-- <van-button type="primary" size="small" @click="sendMessage" :loading="isLoading" icon="share">发送</van-button> -->
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick, onMounted, computed, watch } from 'vue';
import { showToast } from 'vant';
import svgIconPath from '@/assets/1.svg'
import { questions, completions } from "@/api/chatAI";


import { marked } from 'marked'
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'

// 配置 marked
marked.setOptions({
  highlight: (code, lang) => {
    const language = hljs.getLanguage(lang) ? lang : 'plaintext'
    return hljs.highlight(code, { language }).value
  },
  langPrefix: 'hljs language-',
  breaks: true
})
const props = defineProps({
  content: {
    type: String,
    required: true
  },
  sanitize: {
    type: Boolean,
    default: true
  }
})
const htmlContent = (content) => {
  if (!content) return '' // ✅ 添加空值处理
  const rawHtml = marked.parse(content)
  return props.sanitize ? DOMPurify.sanitize(rawHtml) : rawHtml
}

// 配置项
const THINKING_MARKER = '</think>';
const AI_RESPONSE_TYPE = {
  THINKING: 'thinking',
  ANSWER: 'answer'
};

// 响应式数据
const messages = reactive([]);
const inputMessage = ref('');
const messageContainer = ref(null);
const isLoading = ref(false);

// 消息处理逻辑
const createMessage = (role, content = '') => ({
  role,
  thinking: '',
  answer: content,
  isThinking: false,
  loading: role === 'assistant',
  responsePhase: AI_RESPONSE_TYPE.THINKING
});
// 流式响应处理
const processContentChunk = (chunk, currentMessage) => {
  let buffer = chunk;

  while (buffer.length > 0) {
    switch (currentMessage.responsePhase) {
      case AI_RESPONSE_TYPE.THINKING:
        const markerIndex = buffer.indexOf(THINKING_MARKER);
        if (markerIndex === -1) {
          currentMessage.thinking += buffer;
          buffer = '';
        } else {
          currentMessage.thinking += buffer.substring(0, markerIndex);
          currentMessage.responsePhase = AI_RESPONSE_TYPE.ANSWER;
          buffer = buffer.substring(markerIndex + THINKING_MARKER.length);
          currentMessage.isThinking = false;
        }
        break;

      case AI_RESPONSE_TYPE.ANSWER:
        currentMessage.answer += buffer;
        buffer = '';
        break;
    }
  }
};

const processStreamResponse = async (response) => {
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      buffer += decoder.decode(value, { stream: true });

      // 处理完整行
      let boundary;
      while ((boundary = buffer.indexOf('\n')) >= 0) {
        const line = buffer.slice(0, boundary).trim();
        buffer = buffer.slice(boundary + 1);

        if (!line.startsWith('data: ')) continue;

        const dataContent = line.slice(6);
        if (dataContent === '[DONE]') break;

        try {
          const json = JSON.parse(dataContent);
          const chunk = json.choices?.[0]?.delta?.content || '';
          const currentMessage = messages[messages.length - 1];

          processContentChunk(chunk, currentMessage);
          currentMessage.loading = false;
          currentMessage.isThinking = currentMessage.responsePhase === AI_RESPONSE_TYPE.THINKING;

          requestAnimationFrame(scrollToBottom);
        } catch (e) {
          console.error('解析错误:', e);
        }
      }
    }
  } finally {
    messages[messages.length - 1].loading = false;
    scrollToBottom();
  }
};

const sendMessage = async () => {
  if (!inputMessage.value.trim()) return;

  try {
    requestAnimationFrame(scrollToBottom);
    isLoading.value = true;

    // 添加用户消息
    messages.push(createMessage('user', inputMessage.value.trim()));

    // 添加AI消息占位
    messages.push(createMessage('assistant'));

    // 模拟API调用
    const response = await fetch(import.meta.env.VITE_BASE_API + '/api/index/completions', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ content: inputMessage.value, stream: true })
    });
    inputMessage.value = '';
    await processStreamResponse(response);
  } catch (error) {
    console.error('请求失败:', error);
  } finally {
    isLoading.value = false;
  }
};





// 状态管理
// const chatStore = useChatStore();

// 数据绑定
// const inputMessage = ref('你好！');
// const messageContainer = ref(null);
// const isLoading = ref(false);
// const userAvatar = 'https://img.yzcdn.cn/vant/user.jpg';
// const aiAvatar = 'https://img.yzcdn.cn/vant/ai-avatar.png';
// const active = ref(0);

// 消息列表
// const messages = reactive([
//   {
//     role: 'assistant',
//     content: '您好！我是AI助手，有什么可以帮您？',
//     loading: false,
//     thinking: '深度思考中...',
//     answer: '正式回答：您好！我是AI助手，有什么可以帮您？',
//   }
// ]);

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messageContainer.value) {
      messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
    }
  });
};

// 发送消息
// const sendMessage = async () => {
//   if (!inputMessage.value.trim()) {
//     showToast('请输入有效内容');
//     return;
//   }
//   try {
//     isLoading.value = true;
//     // 添加用户消息
//     messages.push({
//       role: 'user',
//       content: inputMessage.value.trim(),
//       loading: false
//     });

//     // 添加AI消息占位
//     messages.push({
//       role: 'assistant',
//       content: '',
//       loading: true
//     });
//     // 调用API（示例使用模拟方法）
//     // await mockStreamResponse();
//     // 实际API调用示例（需替换为真实接口）
//     const response = await fetch('http://ymt.handanzhujian.com/api/index/completions', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json',
//         // 'Authorization': `Bearer ${chatStore.apiKey}`
//       },
//       body: JSON.stringify({ content: inputMessage.value, stream: true })
//     });
//     // 清空输入框
//     inputMessage.value = '';
//     await processStreamResponse(response);
//     /*
//     const response = await fetch('/api/chat', {
//       method: 'POST',
//       headers: {
//         'Content-Type': 'application/json',
//         'Authorization': `Bearer ${chatStore.apiKey}`
//       },
//       body: JSON.stringify({ message: inputMessage.value })
//     });

//     await processStreamResponse(response);
//     */
//     scrollToBottom();
//   } catch (error) {
//     showToast('请求失败: ' + error.message);
//     console.log('请求失败: ', error);

//   } finally {
//     isLoading.value = false;
//     messages[messages.length - 1].loading = false;
//   }
// };

// 流式处理（真实API使用）
// const processStreamResponse = async (response) => {
//   const reader = response.body.getReader();
//   console.log('reader', reader);
//   const decoder = new TextDecoder();
//   let result = '';
//   let content = '';
//   while (true) {
//     const { done, value } = await reader.read();
//     console.log(done, value);
//     if (done) break;
//     // 解码分块数据
//     const chunk = decoder.decode(value, { stream: true });
//     result += chunk;
//     // 处理 SSE 格式（按 "data: " 分割事件）
//     const lines = result.split(/\r\n|\r|\n/);
//     result = lines.pop() || ''; // 保留未完成的行

//     for (const line of lines) {
//       if (line.startsWith('data: ')) {
//         const jsonStr = line.replace('data: ', '');
//         try {
//           const data = JSON.parse(jsonStr);
//           // 提取并拼接内容
//           if (data.choices && data.choices[0].delta.content) {
//             const contentChunk = data.choices[0].delta.content;
//             console.log('收到内容:', contentChunk);
//             // 更新 UI（示例：逐字输出到页面）
//             // content
//             setTimeout(() => {
//               messages[messages.length - 1].content += contentChunk;;
//               messages[messages.length - 1].loading = false;
//               scrollToBottom();
//             }, 2000);
//           }
//         } catch (err) {
//           console.error('解析 JSON 失败:', err);
//         }
//       }
//     }
//   }
// };
// const processStreamResponse = async (response) => {
//   const reader = response.body.getReader();
//   const decoder = new TextDecoder();
//   let buffer = '';

//   while (true) {
//     const { done, value } = await reader.read();
//     if (done) break;

//     buffer += decoder.decode(value, { stream: true });

//     let boundary;
//     while ((boundary = buffer.indexOf('\n')) >= 0) {
//       const line = buffer.slice(0, boundary).trim();
//       buffer = buffer.slice(boundary + 1);

//       if (!line.startsWith('data: ')) continue;

//       // 提取有效数据部分
//       const dataContent = line.slice(6); // 去掉 "data: "

//       // 处理结束标记 [DONE]
//       if (dataContent === '[DONE]') {
//         console.log('Stream completed');
//         messages[messages.length - 1].loading = false;
//         scrollToBottom();
//         continue; // 跳过 JSON 解析
//       }

//       try {
//         const json = JSON.parse(dataContent);
//         const chunk = json.choices?.[0]?.delta?.content || '';

//         // 实时更新 UI
//         if (chunk) {
//           messages[messages.length - 1].content += chunk;
//           messages[messages.length - 1].loading = false;
//           requestAnimationFrame(scrollToBottom);
//         }
//       } catch (e) {
//         console.error('解析错误，跳过无效数据:', dataContent);
//       }
//     }
//   }

//   // 处理剩余 buffer（最后可能有不完整行）
//   if (buffer.trim()) {
//     try {
//       const json = JSON.parse(buffer.trim().replace('data: ', ''));
//       const chunk = json.choices?.[0]?.delta?.content || '';
//       messages[messages.length - 1].content += chunk;
//     } catch {
//       // 忽略最终解析错误
//     }
//   }
//   messages[messages.length - 1].loading = false;
//   scrollToBottom();
// };

// 获取热门问题列表 /api/index/questions
const active = ref(0);
const questionsList = ref([]); // 存储列表数据
const fetchData_questions = async () => {
  try {
    const response = await questions();
    console.log(response);
    if (response.code != 1) {
      throw new Error('获取数据失败');
    }
    questionsList.value = response.data;
  } catch (err) {
  } finally {
  }
};
const sendQuestionsMessage = async (data) => {
  try {
    // 添加用户消息
    messages.push(createMessage('user', data.title));

    // 添加AI消息占位
    messages.push(createMessage('assistant', data.content));
    const currentMessage = messages[messages.length - 1];
    currentMessage.loading = false;
    requestAnimationFrame(scrollToBottom);
  } catch (err) {
  } finally {
  }
};


onMounted(() => {
  fetchData_questions();
  messages.push(createMessage('assistant', '您好！我是AI助手，有什么可以帮您？'));
  const currentMessage = messages[messages.length - 1];
  currentMessage.loading = false;
  scrollToBottom();
});
</script>

<style scoped>
.chat-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.message-container {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  padding-bottom: 60px;
}

.message {
  display: flex;
  margin: 12px 0;
  gap: 8px;

  &.user {
    flex-direction: row-reverse;

    .bubble {
      background: #d1e7dd;
      border-radius: 12px 0 12px 12px;
      overflow-y: visible;

      &::before {
        content: '';
        position: absolute;
        right: -8px;
        top: 12px;
        border: 8px solid transparent;
        border-left-color: #d1e7dd;
      }
    }
  }

  &.assistant {
    .bubble {
      background: #ffffff;
      border-radius: 0 12px 12px 12px;

      &::before {
        content: '';
        position: absolute;
        left: -8px;
        top: 12px;
        border: 8px solid transparent;
        border-right-color: #ffffff;
      }
    }
  }
}

.bubble {
  position: relative;
  max-width: 90%;
  /* 防止内容过短 */
  /* min-width: 40%; */
  padding: 12px;
  font-size: 14px;
  line-height: 1.5;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  /* 强制换行 */
  /* word-wrap: break-word; */
  /* 隐藏溢出内容 */
  /* overflow: hidden; */
  overflow-y: auto;
  /* 滚动条 */
}

.input-area {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  display: flex;
  align-items: center;
  padding: 8px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);

  :deep(.van-field) {
    flex: 1;
    margin-right: 8px;
    background: #f8f8f8;
    border-radius: 18px;
    padding: 6px 12px;
  }
}

/* 暗黑模式适配 */
@media (prefers-color-scheme: dark) {
  .chat-page {
    background: #1a1a1a;
  }

  .bubble {
    color: #ffffff;
  }

  .message.assistant .bubble {
    background: #2d2d2d;

    &::before {
      border-right-color: #2d2d2d;
    }
  }

  .input-area {
    background: #2d2d2d;

    :deep(.van-field) {
      background: #3d3d3d;
      color: #ffffff;
    }
  }
}
</style>

<style scoped>
/* 消息气泡样式 */
.message {
  margin: 12px 0;
  transition: all 0.3s ease;

  &.assistant {
    .bubble {
      background: rgba(255, 255, 255, 0.9);
      border-radius: 12px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .thinking-phase {
        color: #666;
        padding: 12px;
        border-left: 3px solid #4CAF50;
        background: rgba(76, 175, 80, 0.05);
      }

      .answer-phase {
        padding: 12px;

        .answer-header {
          color: #2196F3;
          font-weight: bold;
          margin-bottom: 0px;
        }

        .answer-content {
          line-height: 1.6;
          white-space: pre-wrap;
        }
      }
    }

    &.thinking {
      opacity: 0.8;
      transform: translateY(5px);

      .bubble {
        background: rgba(245, 245, 245, 0.9);
      }
    }
  }
}

/* 输入区域优化 */
.input-area {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(5px);
  box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.05);

  :deep(.van-field) {
    background: rgba(245, 245, 245, 0.8);
    border-radius: 20px;
    transition: all 0.3s ease;

    &:focus-within {
      background: white;
      box-shadow: 0 2px 8px rgba(76, 175, 80, 0.15);
    }
  }
}

/* 动画效果 */
/* @keyframes thinking-pulse {
  0% {
    opacity: 0.8;
  }

  50% {
    opacity: 1;
  }

  100% {
    opacity: 0.8;
  }
}

.thinking-icon {
  animation: thinking-pulse 1.5s infinite;
  margin-right: 8px;
} */
</style>